package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.kms.aliyun.http.HttpRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.apache.catalina.connector.Response;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.persistence.SequenceMapper;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

//import javax.jws.WebParam;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    @Autowired
    private SequenceMapper sequenceMapper;

    @GetMapping("/listOrders")
    public String listOrders(HttpSession session,Model model){
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        List<Order> orderList = orderService.getOrdersByUsername(username);
        session.setAttribute("orderList", orderList);
        model.addAttribute("orderList", orderList);
        return "order/listOrders";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(HttpSession session,Model model,@RequestParam("orderId") String orderId){
        int id = Integer.parseInt(orderId);
        Order order=null;
        if(id!=0){
            order = orderService.getOrder(id);
            if(order!=null){
                session.setAttribute("order",order);
                model.addAttribute("order",order);
                return "order/viewOrder";
            }
        }
        return "order/listOrders";
    }

    @PostMapping("/newOrder")
    public void newOrder(HttpServletResponse resp, HttpSession session, Model model) throws IOException {
        Order order = (Order) session.getAttribute("tempOrder");
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        Account account = (Account) session.getAttribute("account");
        if(order!=null){
            orderService.insertOrder(order);
            session.setAttribute("order",order);
            model.addAttribute("order",order);
            String username = account.getUsername();
            for (int i = 0; i < cart.size(); i++){
                cartService.updateItemByItemIdAndPay(username, cart.get(i).getItem().getItemId(),true);
            }
            //清空购物车
            session.removeAttribute("cart");
            cart = null;
            if(cart == null){
                cart = new ArrayList<CartItem>();
            }
            cart = cartService.selectItemByUsername(username);
            session.setAttribute("cart",cart);
            model.addAttribute("cart",cart);
            session.setAttribute("message", "Thank you, your order has been submitted.");
            result.setCode(16);
            Sequence sequence = new Sequence("ordernum", -1);
            sequence = sequenceMapper.getSequence(sequence);
            int temp = sequence.getNextId()-1;
            order.setOrderId(temp);
            session.setAttribute("order",order);
            //String url = "/order/viewOrder?orderId="+String.valueOf(temp);
//            return "order/order";
            //result.setMsg(url);
            result.setMsg("/order/alipay");
            String str = JSON.toJSONString(result);
            out.print(str);
            out.flush();
            out.close();
        }else{
            session.setAttribute("message", "An error occurred processing your order (order was null).");
        }
    }

    @GetMapping(value = "/alipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String alipay(HttpServletRequest request,HttpSession session,Model model,HttpServletResponse resp)throws AlipayApiException{
        //获取暂时生成的订单
        Order order = (Order) request.getSession().getAttribute("tempOrder");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = UUID.randomUUID().toString().replace("-","");;
        //付款金额
        BigDecimal total_amount = order.getTotalPrice();
        //订单名称
        String subject =String.valueOf(order.getOrderDate())+order.getOrderId();
        //商品描述
        String body = "用户名：" + order.getUsername();
        //该笔订单允许的最晚付款时间，逾期将关闭交易。
        String timeout_express = "5m";
        //设置信息
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
}
